package comm;

import main.Manager;
import display.DisplayManager;


/**Describes a message being exchanged.
 * 
 * @author Bruno Zumba (04/10/2011)
 *
 */
public class Message {
	
	private String receiver; //The IP that must receive the message
	private String sender; //The IP that sent the message
	private String msg; //The string the contains the whole message
	
	private int type;
	
	public Message(){
		msg = new String();
		receiver = new String();
	}
	public void decodeMessage(String msg){
		this.msg = msg;
		
		//Get the receiver ip
		int i;
		int j;
		for(i = 0; msg.charAt(i) != ':'; i++){}
		for(; (msg.charAt(i) == ' ') || (msg.charAt(i) == '"') || (msg.charAt(i) == ':'); i++){}
		
		for(j = i; ((msg.charAt(j) != '\n') && (msg.charAt(j) != ' ') && (msg.charAt(j) != '"') && (msg.charAt(j) != ',')); j++){}
		
		//The receiver IP is in the string beginning in i and ending in j
		receiver = new String(msg.substring(i, j));
		
		//Get the sender ip
		for(i=j; msg.charAt(i) != ':'; i++){}
		for(; (msg.charAt(i) == ' ') || (msg.charAt(i) == '"') || (msg.charAt(i) == ':'); i++){}
		for(j = i; ((msg.charAt(j) != '\n') && (msg.charAt(j) != ' ') && (msg.charAt(j) != '"') && (msg.charAt(j) != ',')); j++){}
		
		sender = new String(msg.substring(i,j));
		
	}

	public void createDisconnectMessage(String sender){
		type = Manager.DISCONNECT;
		this.sender = sender;
		this.receiver = DisplayManager.getDisplayIp();
		msg = msg.concat("" +
				"{" +
				"	Receiver: "+this.receiver+",\n" +
				"	Sender: "+this.sender+",\n" +
				"	Type: "+type+"\n" +
				"	BodySize: 0\n" +
				"}");
	}
	
	public void createConnectMessage(String sender, String encryptedMessage){
		type = Manager.CONNECT;
		this.sender = sender;
		this.receiver = DisplayManager.getDisplayIp();
		
		msg = msg.concat("" +
				"{" +
				"	Receiver: "+this.receiver+",\n" +
				"	Sender: "+this.sender+",\n" +
				"	Type: "+type+"\n" +
				"	BodySize: 0\n" +
				"}");
	}
	
	public String getReceiver(){
		return this.receiver;
	}
	public String getMsg(){
		return this.msg;
	}
	public int getType(){
		return this.type;
	}
	public String getSender(){
		return this.sender;
	}

}
